import {colorUISdk} from "../../config/mp-sdk";

Page({
    data: {
        members: [],
        page: 1,
        limit: 20,
        loading: false,
        noMore: false,
        startDate: '',           // 筛选日期，完整yyyy-mm-dd
        pickerVisible: false,    // 控制picker显隐
        groupedLogs: [],
        isRefreshing: false, // 下拉刷新状态
    },

    onLoad() {
        this.loadMembers();
    },


    // 点击顶部时间栏，显示picker
    onTimeTap() {
        this.setData({pickerVisible: true});
    },

    onPickerCancel() {
        this.setData({pickerVisible: false});
    },

    // 选择日期后，刷新数据
    bindDateChange(e) {
        const newDate = e.detail.value;
        this.setData({
            members: [],
            page: 1,
            limit: 5,
            loading: false,
            noMore: false,
            startDate: newDate,
            pickerVisible: false,    // 控制picker显隐
            groupedLogs: [],
            isRefreshing: false // 下拉刷新状态

        }, () => {
            this.loadMembers();
        });
    },

    // 下拉中（可选）
    onPulling() {
        console.log('用户正在下拉...');
    },

    onRefresh() {
        let {startDate} = this.data;

        if (!startDate) {
            // 如果没选过日期，默认为当前月
            const now = new Date();
            startDate = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}-01`;
        }

        const date = new Date(startDate);
        const currentYear = date.getFullYear();
        const currentMonth = date.getMonth(); // 0-based

        const now = new Date();
        const nowYear = now.getFullYear();
        const nowMonth = now.getMonth(); // 0-based

        // 如果当前 startDate 不是当前系统月份，才+1
        if (currentYear < nowYear || (currentYear === nowYear && currentMonth < nowMonth)) {
            // 月份 +1
            date.setMonth(currentMonth + 1);
        }

        const newYear = date.getFullYear();
        const newMonth = String(date.getMonth() + 1).padStart(2, '0');

        const newStartDate = `${newYear}-${newMonth}`;

        this.setData({
            startDate: newStartDate,
            page: 1,
            noMore: false,
            members: [],
            groupedLogs: [],
            isRefreshing: true
        }, () => {
            this.loadMembers(true);
        });
    },


    // 刷新动画恢复完成（可选）
    onRestore() {
        console.log('刷新动画复原完成');
    },


    // 滚动到底部触发加载更多
    onReachBottom() {
        if (!this.data.loading && !this.data.noMore) {
            this.loadMembers();
        }
    },

    // 加载成员列表
    loadMembers() {
        this.setData({loading: true});
        colorUISdk.request({
            url: 'api/user/member_list',
            method: 'GET',
            data: {
                page: this.data.page,
                limit: this.data.limit,
                date: this.data.startDate
            }
        }).then(res => {
            if (res.code === 1) {
                const newList = res.data.data || [];
                const total = res.data.total || 0;

                this.setData({
                    members: this.data.members.concat(newList),
                    page: this.data.page + 1,
                    isRefreshing: false,
                    noMore: this.data.members.length + newList.length >= total
                });


                // 合并旧数据 + 新数据
                const allLogs = (this.data.groupedLogs.flatMap(g => g.list)).concat(newList);

                const grouped = this.groupLogsByMonth(allLogs);


                this.setData({
                    groupedLogs: grouped
                });

            } else {
                wx.showToast({title: res.msg, icon: 'none'});
            }
        }).finally(() => {
            this.setData({loading: false});
        });
    },

    // 将日志按年月分组
    groupLogsByMonth(logs) {
        const grouped = {};
        logs.forEach(log => {
            const monthKey = log.join_time.slice(0, 7); // '2025-07'
            if (!grouped[monthKey]) {
                grouped[monthKey] = [];
            }
            grouped[monthKey].push(log);
        });

        // 转换为数组并按时间倒序排序
        const sorted = Object.keys(grouped)
            .sort((a, b) => b.localeCompare(a))
            .map(month => ({
                month,
                list: grouped[month]
            }));

        return sorted;
    },


});
